﻿using UnityEngine;
using System.Collections;

public class visionScript : MonoBehaviour {
	public GameObject parent;
    public GameObject fov;
    public Material spottedMat;
    public Material normalMat;
	private LayerMask wallLayer;
    private float playerDistance;
    private float wallDistance; 

	// Use this for initialization
	void Start () {
		wallLayer = LayerMask.GetMask("Unwalkable");
	}
	
	// Update is called once per frame
	void Update () {
	}
	void OnTriggerEnter2D(Collider2D col)
	{
		if (col.tag == "Player") {
            //enemy can shoot when a player is in their vision
            parent.GetComponent<enemyScript>().canShoot = true;
            //check for line of sight on player to trigger enemy attacking mode
            Vector2 target = new Vector2(col.transform.position.x, col.transform.position.y);
			Vector2 myPos = new Vector2(parent.transform.position.x, parent.transform.position.y);
            playerDistance = Vector2.Distance(myPos, target);
			Vector2 direction = target - myPos;
			RaycastHit2D hit = Physics2D.Raycast (myPos, direction);
			if (hit.collider.tag == "Player") {                
				parent.GetComponent<enemyScript> ().isAttacking = true;
                fov.GetComponent<MeshRenderer>().material = spottedMat;
            } else if (hit.collider.tag == "crate") {
				if (!col.GetComponent<playerScript>().inCover) {
					RaycastHit2D checkWalls = Physics2D.Raycast (myPos, direction, 20, wallLayer.value, 0 );
                    if (checkWalls.collider.tag == "wall") { wallDistance = checkWalls.distance; }
                    if (checkWalls.collider.tag != "wall" || wallDistance >= playerDistance)
                    {
                        parent.GetComponent<enemyScript>().isAttacking = true;
                        fov.GetComponent<MeshRenderer>().material = spottedMat;
                    }
				}
			}
		}
	}
    void OnTriggerExit2D(Collider2D col)
    {
        //prevent enemy from shooting in the player has left enemy vision
        if (col.tag == "Player")
        {
            parent.GetComponent<enemyScript>().canShoot = false;
            fov.GetComponent<MeshRenderer>().material = normalMat;
        }
        
    }
}
